<template>
  <div class="main-view file-to-base64-view">
    <div class="title">任意文件转base64</div>
    <div class="upload-buttons">
      <el-upload :auto-upload="false" multiple :show-file-list="false" @change="onChange">
        <el-button type="primary">选择文件</el-button>
      </el-upload>
      <el-button type="danger" style="margin-left: 5px" @click="onClear"> 清空 </el-button>
    </div>
    <div class="base64-list">
      <el-scrollbar :max-height="getMaxHeight" always>
        <el-card
          v-for="(item, idx) in list"
          :key="idx"
          style="width: 100%"
          shadow="hover"
          :body-style="{
            padding: 0
          }"
        >
          <template #header>
            <div class="base64-item-header">
              <div>{{ item.name }}</div>
              <div style="text-align: right; flex: 1">{{ item.size }}</div>
              <div style="text-align: center; margin-left: 10px; margin-right: 10px">
                <el-button type="primary" @change="onCopy">复制</el-button>
              </div>
            </div>
          </template>
          <el-input :model-value="item.data" type="textarea" :rows="8" readonly></el-input>
        </el-card>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive } from 'vue';
import type { UploadFile } from 'element-plus';

const list: Array<{ name: string; size: number; data: string }> = reactive(
  new Array<{
    name: string;
    size: number;
    data: string;
  }>()
);

const getMaxHeight = computed(() => {
  return document.body.offsetHeight - 50 - 30 - 100;
});

const onChange = (file: UploadFile) => {
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      list.push({
        name: file.name,
        size: file.size === undefined ? 0 : file.size,
        data: e.target?.result as string
      });
    };
    reader.onerror = (error) => {
      console.error(error);
    };
    file.raw && reader.readAsDataURL(file.raw);
  }
};

const onCopy = () => {};

const onClear = () => {
  list.splice(0, list.length);
};
</script>

<style scoped lang="scss">
.file-to-base64-view {
  .title {
    height: 50px;
    line-height: 50px;
    margin-bottom: 5px;
    font-size: 18px;
  }
  .upload-buttons {
    margin-bottom: 5px;
    display: flex;
    flex-direction: row;
  }
  .base64-list {
    width: 100%;
    .base64-item-header {
      height: 40px;
      line-height: 40px;
      display: flex;
      flex-direction: row;
    }
  }
}
</style>
